package com.hs.controller;

import com.hs.config.R;
import com.hs.dao.UserGoodMapper;
import com.hs.entity.User;
import com.hs.entity.UserGood;
import com.hs.service.UserGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("userGood")
@Controller
public class UserGoodController {
    @Autowired
    UserGoodService userGoodService;
    @Autowired
    UserGoodMapper userGoodMapper;
    @RequestMapping("insert")
    @ResponseBody
    public R insert(UserGood userGood,HttpSession session){
        User user = (User) session.getAttribute("user");
        if(userGood.getAmount() == null){
            return R.FAILURE("请填写数量",0);
        }
        if(userGood.getGoodId() == null){
            return R.FAILURE("请选择物品",0);
        }
        userGood.setUserId(user.getId());
        UserGood ci = userGoodMapper.getUserGood(userGood);
        int i = 0;
        if(ci != null){
//            return R.FAILURE("此商品已添加库存",0);
            userGood.setAmount(ci.getAmount() + userGood.getAmount());
            i = userGoodService.update(userGood);
        }else{
            i = userGoodService.insert(userGood);
        }

        if(i > 0){
            return R.SUCCESS(userGood.toString(),i);
        }
        return R.FAILURE("",i);
    }


}
